package core

import (
	"github.com/coreos/etcd/clientv3"
	"github.com/spf13/viper"
	"log"
	"time"
)

type Etcd struct {
	Client  *clientv3.Client
	Kv      clientv3.KV
	Lease   clientv3.Lease
	Watcher clientv3.Watcher
}

var (
	GEtcd *Etcd
)

func InitEtcd(Vp *viper.Viper) (err error) {
	var (
		config clientv3.Config
	)
	GEtcd = &Etcd{}
	config = clientv3.Config{
		Endpoints:   Vp.GetStringSlice("etcd.endpoints"),
		DialTimeout: time.Duration(Vp.GetInt("etcd.timeout")) * time.Millisecond,
	}
	if GEtcd.Client, err = clientv3.New(config); err != nil {
		log.Println(err.Error())
		return
	}

	GEtcd.Kv = clientv3.NewKV(GEtcd.Client)
	GEtcd.Lease = clientv3.NewLease(GEtcd.Client)
	GEtcd.Watcher = clientv3.NewWatcher(GEtcd.Client)
	return err
}
